package org.dromara.bykt.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.dromara.bykt.domain.vo.AliOSSProperties;
import org.dromara.common.core.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUpload {
    @Autowired
    private AliOSSProperties aliOSSProperties;

    // 上传图片
    public String uploadImage(MultipartFile file) throws Exception {
        return uploadFile(file, "images/");
    }

    // 上传视频
    public String uploadVideo(MultipartFile file) throws Exception {
        return uploadFile(file, "videos/");
    }

    private String uploadFile(MultipartFile file, String dir) throws Exception {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(), aliOSSProperties.getAccessKeyId(), aliOSSProperties.getAccessKeySecret());

        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 文件路径
            String filePath = dir + DateUtils.datePath() + "/" + fileName;

            // 上传文件流
            ossClient.putObject(aliOSSProperties.getBucketName(), filePath, file.getInputStream());

            // 返回文件URL
            return "https://oss.xxmijuan.com/" + filePath;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
